import {PageContainer} from '@ant-design/pro-layout';
import {List, message, Space} from 'antd';
import React, {useEffect, useState} from 'react';
import LessonFilter from './components/LessonFilter';
import LessonCard from './components/LessonCard';
import './style.less';
import LessonEditForm from "@/pages/lesson-manager/components/LessonEditForm";
import {addLessonAPI, deleteLessonAPI, queryCoachLessonsAPI, updateLessonAPI} from "@/pages/lesson-manager/service";
import LessonDetailModal from "@/pages/lesson-manager/components/LessonDetailModal";
import LessonStudentModal from "@/pages/lesson-manager/components/LessonStudentModal";

const LessonManager: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [lessons, setLessons] = useState<API.ILesson[]>([]);
  const [pagination, setPagination] = useState({current: 1, pageSize: 8, total: 0});
  const [filterParams, setFilterParams] = useState({});
  const [currentLesson, setCurrentLesson] = useState<API.ILesson | null>(null);
  const [visible, setVisible] = useState<boolean>(false);
  const [detailVisible, setDetailVisible] = useState<boolean>(false);
  const fetchLessons = async (params: any = {}) => {
    setLoading(true);
    try {
      // 实际项目中替换为API调用
      const {data} = await queryCoachLessonsAPI({
        ...params,
        current: pagination.current,
        pageSize: pagination.pageSize
      });

      if (data.data) {
        setLessons(data.data);
        setPagination({
          ...pagination,
          total: data.total || 0
        });
      }
    } catch (error) {
      message.error('获取课程列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchLessons(filterParams);
  }, [pagination.current, pagination.pageSize, filterParams]);

  const handleFilterChange = (values: any) => {
    setFilterParams(values);
    setPagination({...pagination, current: 1});
  };

  const handlePageChange = (page: number, pageSize?: number) => {
    setPagination({...pagination, current: page, pageSize: pageSize || pagination.pageSize});
  };

  const handleDelete = async (id: string) => {
    const {data} = await deleteLessonAPI(id);
    if (data) {
      message.success('删除成功');
      await fetchLessons(filterParams);
    }
  };

  return (
    <PageContainer
      style={{minHeight: '80vh'}}
      title="教练课程管理"
      extra={[
        <LessonEditForm
          onSubmit={async (values) => {
            const {data} = await addLessonAPI(values);
            if (data) {
              message.success('创建成功');
              await fetchLessons(filterParams);
            }
            return data
          }}
        />
      ]}
    >
      <Space direction="vertical" size="large" style={{width: '100%'}}>
        <LessonFilter onFilterChange={handleFilterChange}/>
        <List
          loading={loading}
          grid={{gutter: 16, xs: 1, sm: 2, md: 2, lg: 4, xl: 4, xxl: 4}}
          dataSource={lessons}
          renderItem={(item) => (
            <List.Item>
              <LessonCard
                lesson={item}
                onStudent={(lesson) => {
                  setVisible(true)
                  setCurrentLesson(lesson)
                }}
                onEdit={async (values: API.ILesson) => {
                  const {data} = await updateLessonAPI({...values, id: item.id, version: item.version})
                  if (data) {
                    message.success('更新成功')
                    await fetchLessons(filterParams)
                  }
                  return data
                }}
                onDelete={handleDelete}
                onStop={async (lesson) => {
                  if (lesson.status === '1') {
                    lesson.status = '3'
                  } else if (lesson.status === '3') {
                    lesson.status = '1'
                  }
                  const {data} = await updateLessonAPI({
                    status: lesson.status,
                    id: item.id,
                    version: item.version
                  } as any)
                  if (data) {
                    message.success('更新成功')
                    await fetchLessons(filterParams)
                  }
                  return data
                }}
                onDetail={(values: API.ILesson) => {
                  setDetailVisible(true)
                  setCurrentLesson(values)
                }}/>
            </List.Item>
          )}
          pagination={{
            ...pagination,
            onChange: handlePageChange,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条课程`
          }}
        />
      </Space>
      <LessonDetailModal
        visible={detailVisible}
        onCancel={() => setDetailVisible(false)}
        lesson={currentLesson || undefined}
      />
      {
        currentLesson && <LessonStudentModal
          visible={visible}
          onCancel={() => {
            setVisible(false)
          }}
          lesson={currentLesson}
        />
      }

    </PageContainer>
  );
};

export default LessonManager;
